// RTFContentCtrl.cpp : Defines the initialization routines for the DLL.
//

#include "stdafx.h"
#include "RTFContentCtrl.h"
#include "RTFContentControl.h"

#include "..\3rdparty\compression.h"
#include "..\3rdparty\textfile.h"

#include "..\shared\filemisc.h"
#include "..\shared\misc.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

// from r2h.h
typedef int (*PFNCONVERTRTF2HTML)(const char*, const char*, unsigned long, const char*);

/*
static AFX_EXTENSION_MODULE AfxdllDLL = { NULL, NULL };

extern "C" int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
	// Remove this if you use lpReserved
	UNREFERENCED_PARAMETER(lpReserved);

	if (dwReason == DLL_PROCESS_ATTACH)
	{
		TRACE0("AFXDLL.DLL Initializing!\n");
		
		// Extension DLL one-time initialization
		if (!AfxInitExtensionModule(AfxdllDLL, hInstance))
			return 0;

		// Insert this DLL into the resource chain
		// NOTE: If this Extension DLL is being implicitly linked to by
		//  an MFC Regular DLL (such as an ActiveX Control)
		//  instead of an MFC application, then you will want to
		//  remove this line from DllMain and put it in a separate
		//  function exported from this Extension DLL.  The Regular DLL
		//  that uses this Extension DLL should then explicitly call that
		//  function to initialize this Extension DLL.  Otherwise,
		//  the CDynLinkLibrary object will not be attached to the
		//  Regular DLL's resource chain, and serious problems will
		//  result.

		new CDynLinkLibrary(AfxdllDLL);
	}
	else if (dwReason == DLL_PROCESS_DETACH)
	{
		TRACE0("AFXDLL.DLL Terminating!\n");
		// Terminate the library before destructors are called
		AfxTermExtensionModule(AfxdllDLL);
	}
	return 1;   // ok
}
*/

static CRTFContentCtrlApp theApp;

DLL_DECLSPEC IContent* CreateContentInterface()
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

	return &theApp;
//	return new CRTFContentCtrlApp;
}

DLL_DECLSPEC int GetInterfaceVersion() 
{ 
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

	return ICONTENTCTRL_VERSION; 
}

CRTFContentCtrlApp::CRTFContentCtrlApp()
{
}

const char* CRTFContentCtrlApp::GetTypeID() const
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

	static CString sID;

	Misc::GuidToString(RTF_TYPEID, sID); 

	return sID;
}

const char* CRTFContentCtrlApp::GetTypeDescription() const
{
	return _T("Rich Text");
}

IContentControl* CRTFContentCtrlApp::CreateCtrl(unsigned short nCtrlID, unsigned long nStyle, 
						long nLeft, long nTop, long nWidth, long nHeight, HWND hwndParent)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

	// load localized resources
	HINSTANCE hResDll = LoadLibrary("RTFContentCtrlLOC.dll");

	if (hResDll)
		AfxSetResourceHandle(hResDll);

	CRTFContentControl* pControl = new CRTFContentControl;

	if (pControl)
	{
		CRect rect(nLeft, nTop, nLeft + nWidth, nTop + nHeight);

		if (pControl->Create(nStyle, rect, CWnd::FromHandle(hwndParent), nCtrlID, TRUE))
		{
			return pControl;
		}
	}

	delete pControl;
	return NULL;
}

void CRTFContentCtrlApp::Release()
{
//	AFX_MANAGE_STATE(AfxGetStaticModuleState());
//	delete this;
}

int CRTFContentCtrlApp::ConvertToHtml(const unsigned char* pContent, int nLength, 
									  const char* szCharSet, char*& szHtml)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

	if (nLength == 0)
		return 0; // nothing to convert

	// we may have to decompress it first
	unsigned char* pDecompressed = NULL;

	if (strncmp((const char*)pContent, RTFTAG, LENTAG) != 0)
	{
		int nLenDecompressed = 0;

		if (Compression::Decompress(pContent, nLength, pDecompressed, nLenDecompressed))
		{
			pContent = pDecompressed;
			nLength = nLenDecompressed;
		}
		else
			return 0;
	}

	// copy rtf to CString
	CString sRtf((LPCSTR)pContent, nLength), sHtml;
	nLength = 0; // reuse for resultant html length

	// try loading our new converter
	CString sRtf2HtmlPath = FileMisc::GetModuleFolder() + "rtf2htmlbridge.dll";
	static HMODULE hMod = LoadLibrary(sRtf2HtmlPath);

	if (hMod)
	{
		typedef int (*PFNCONVERTRTF2HTML)(const char*, const char*, const char*, 
			const char*, const char*, const char*, 
			const char*, const char*, const char*, 
			const char*, const char*);
		
		PFNCONVERTRTF2HTML fnRtf2Html = (PFNCONVERTRTF2HTML)GetProcAddress(hMod, "fnRtf2Html");

		if (fnRtf2Html)
		{
			CString sTempRtf = FileMisc::GetTempFileName("Rtf2Html", "rtf");
			FileMisc::SaveFile(sTempRtf, sRtf, sRtf.GetLength());

			// arguments
			// create a unique image folder every time this is called for this session
			static int nImgCount = 1;
			CString sImgDir, sCharSet;

			sCharSet.Format("/CS:%s", szCharSet);

			sImgDir.Format("/ID:images%d", nImgCount);
			nImgCount++;

			CString sTempHtml = FileMisc::GetTempFileName("Rtf2Html", "html");

			try
			{
				nLength = 0;
				int nRet = fnRtf2Html(sTempRtf, FileMisc::GetTempFolder(), sImgDir, 
									  "/IT:png", "/DS:content", sCharSet, "", "", "", "", "");
				if (nRet)
				{
					CTextFileRead file(sTempHtml);
					file.Read(sHtml);
					//FileMisc::LoadFile(sTempHtml, sHtml);
					nLength = sHtml.GetLength();
				}
			}
			catch (...)
			{
				// nLength = 0
			}

			// cleanup
			DeleteFile(sTempRtf);
			DeleteFile(sTempHtml);
		}
	}

	if (nLength)
	{
		szHtml = new char[nLength + 1];

		memcpy(szHtml, sHtml, nLength);
		szHtml[nLength] = 0;
	}

	delete [] pDecompressed;

	return nLength;
}
